package com.zhiyun.hxzy.service;

import com.zhiyun.hxzy.dao.ErrorLogDao;
import com.zhiyun.hxzy.domain.ErrorLog;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Optional;

@Service
@Transactional
public class ErrorLogService {
    @Autowired
    private ErrorLogDao errorLogDao;

    public void addErrorLog(ErrorLog errorLog){
        errorLogDao.save(errorLog);
    }

    public ErrorLog findById(Long id){
        Optional<ErrorLog> byId = errorLogDao.findById(id);
        return byId.get();
    }
    public Page<ErrorLog> findAll(int pageNum, int pageSize, String username,String visitTime){
        Specification<ErrorLog> specification =  new Specification<ErrorLog>() {
            @Override
            public Predicate toPredicate(Root<ErrorLog> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate predicate = criteriaBuilder.like(root.get("username").as(String.class), "%"+username+"%");
                Predicate predicate2 = criteriaBuilder.like(root.get("visitTime").as(String.class), "%"+visitTime+"%");
                Predicate allPredicat = criteriaBuilder.and(predicate, predicate2);
                return allPredicat;
            }
        };
        if(pageNum<0){
            pageNum=0;
        }

        Pageable pageable= PageRequest.of (pageNum,pageSize,Sort.by(Sort.Direction.DESC,"id"));
        Page errorLogs = errorLogDao.findAll(specification,pageable);
        return errorLogs;
    }
}
